"use client";
import { useGetStatics, useGetTaskList } from "@/service/align";
import {
  CheckCircleTwoTone,
  ExclamationCircleTwoTone,
  SendOutlined,
  SyncOutlined,
} from "@ant-design/icons";
import { Box, Container, Paper, Typography } from "@mui/material";
import { useQueryClient } from "@tanstack/react-query";
import {
  Col,
  Pagination,
  PaginationProps,
  Row,
  Statistic,
  Table,
  type TableProps,
} from "antd";
import React, { useEffect, useRef, useState } from "react";
import CountUp from "react-countup";

interface DataType {
  id: string;
  pid: string;
  status: string;
  workspace: string;
  workspace_dir: string;
  cmd: string;
  finish_time: string;
  update_time: string;
  create_time: string;
  email: string;
}

const columns: TableProps<DataType>["columns"] = [
  {
    title: "Task ID",
    dataIndex: "id",
  },
  // {
  //   title: "Email",
  //   dataIndex: "email",
  //   render: (text) => {
  //     return (
  //       <div
  //         style={{
  //           overflow: "hidden",
  //           textOverflow: "ellipsis",
  //           whiteSpace: "nowrap",
  //           width: "160px",
  //         }}
  //       >
  //         {text}
  //       </div>
  //     );
  //   },
  // },
  {
    title: "Status",
    dataIndex: "status",
    width: 100,
    render: (text) => (
      <div style={{ display: "flex", alignItems: "center" }}>
        <div style={{ marginRight: "7px" }}>
          {text == "success" && <CheckCircleTwoTone twoToneColor="#52c41a" />}
          {text == "pending" && (
            <SendOutlined style={{ color: "rgb(56, 116, 203)" }} />
          )}
          {text == "running" && (
            <SyncOutlined spin style={{ color: "#52c41a" }} />
          )}
          {text == "canceled" && (
            <ExclamationCircleTwoTone twoToneColor="#fbbf24" />
          )}
        </div>
        {text}
      </div>
    ),
  },
  {
    title: "Workspace",
    dataIndex: "workspace",
  },
  {
    title: "Start Time",
    dataIndex: "create_time",
  },
  {
    title: "PID",
    dataIndex: "pid",
    render: (text) => {
      return <div>{text || 0}</div>;
    },
  },
  {
    title: "Finish Time",

    dataIndex: "finish_time",
    render: (text) => {
      return <div>{text || "Not finished yet"}</div>;
    },
  },
];

const formatter: any = (value: number) => <CountUp end={value} separator="," />;

const App: React.FC = () => {
  const [page, setPage] = useState(1);
  const {
    isLoading,
    data: taskList,
    refetch: refreshTaskList,
  } = useGetTaskList(page);

  const { data: Count, refetch: refreshStatics } = useGetStatics();
  const isRequest = useRef(false);
  const queryClient = useQueryClient();

  const onShowSizeChange: PaginationProps["onShowSizeChange"] = (current) => {
    setPage(current);
  };

  useEffect(() => {
    const data = queryClient.getQueriesData({ queryKey: ["tasks", page] });
    if (data[0][1]) {
      refreshTaskList();
      refreshStatics();
    }
  }, [page, refreshStatics, refreshTaskList, queryClient]);

  useEffect(() => {
    if (!isRequest.current) {
      isRequest.current = true;
      refreshTaskList();
      refreshStatics();
    }
  }, [refreshTaskList, refreshStatics]);

  var timestamp = new Date().getTime();
  return (
    <Box>
      <Container
        sx={{
          display: "flex",
          flexDirection: "column",
          pt: { xs: 14, sm: 20 },
          pb: { xs: 8, sm: 12 },
        }}
      >
        <Paper sx={{ padding: "1rem" }}>
          <div
            style={{
              textAlign: "center",
            }}
          >
            <Typography
              sx={{ marginTop: "1rem", marginBottom: "1rem" }}
              variant="h5"
              component="div"
            >
              Task{" "}
              <Box component="span" sx={{ color: "primary.main" }}>
                Queue
              </Box>
            </Typography>
            <div
              style={{
                marginBottom: "32px",
              }}
            >
              <Row gutter={7} style={{ width: "100%" }}>
                <Col span={6}>
                  <Statistic
                    title="Success Tasks"
                    value={Count?.success}
                    precision={2}
                    formatter={formatter}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="Queue Tasks"
                    value={Count?.pending}
                    precision={2}
                    formatter={formatter}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="Running Tasks"
                    value={Count?.running}
                    precision={2}
                    formatter={formatter}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="Time Stamps"
                    value={timestamp}
                    precision={2}
                    formatter={formatter}
                  />
                </Col>
              </Row>
            </div>
          </div>
          <Table
            columns={columns}
            dataSource={taskList?.results}
            loading={isLoading}
            rowKey={"id"}
            pagination={false}
          />
          {taskList?.results && (
            <div
              style={{
                marginTop: "0.5rem",
                display: "flex",
                justifyContent: "center",
              }}
            >
              <Pagination
                onChange={onShowSizeChange}
                defaultCurrent={1}
                current={page}
                showSizeChanger={false}
                total={taskList.count || 0}
              />
            </div>
          )}
        </Paper>
      </Container>
    </Box>
  );
};

export default App;
